/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmCostIncomeController
 * 项目财务成本与确认收入
 *
 * 修改纪录
 * 2020-05-19 版本：1.0 shenyouyi 创建。
 * @version 版本：1.0
 * @author 作者：shenyouyi
 * 创建日期：2020-05-19
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.pm.controller.auto.PmCostIncomeControllerAuto;
import com.topscomm.pm.pojo.PmCostIncomeEntity;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.service.impl.PmProjectService;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: shenyouyi
 * @date: 2020-05-19
 * @description:项目财务成本与确认收入Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/costIncome")
public class PmCostIncomeController extends PmCostIncomeControllerAuto implements IPmCostIncomeController {

	@Resource
	private PmProjectService pmProjectService;

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-19
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_month")) {
			String value = paraMap.get("qry_month").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and financialmonth = {0} ", SQLAdapter.toDateLong(value));
		}
		sql .appendSingle(this.spellingSqlForProject(paraMap, "PmCostIncome","projectid","id"));

		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Insert, "","PmCostIncome", this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" and " + MisStringUtil.createWhereByUsercodeFromProject(this.getUserBean().getUser(), "projectid", service.getDao().getTableName()));
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-19
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 设置显示字段
	  **/
	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		super.afterLoad(paraMap);
		if(paraMap.get("projectid")==null){
			return;
		}
		String projectid = paraMap.get("projectid").toString();
		PmProjectEntity pmProjectEntity = pmProjectService.queryById(projectid);
		Date planstarttime = null, planendtime = null, actualstarttime = null, actualendtime = null;
		if(pmProjectEntity != null){
			planstarttime = pmProjectEntity.getPlanstarttime();
			planendtime = pmProjectEntity.getPlanendtime();
			actualstarttime = pmProjectEntity.getActualstarttime();
			actualendtime = pmProjectEntity.getActualendtime();
		}
		paraMap.put("planstarttime", planstarttime);
		paraMap.put("planendtime", planendtime);
		paraMap.put("actualstarttime", actualstarttime);
		paraMap.put("actualendtime", actualendtime);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 新增财务收入与确认
	  **/
	@Override
	@PostMapping(value = "/insert")
	public ResponseResult<Object> insert(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 进行检验
		Long projectid = (Long)paraMap.get("projectid");
		String financialmonth = (String)paraMap.get("financialmonth");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("projectid = {0} and financialmonth = to_date('{1}','yyyy-mm-dd hh24:mi:ss')", projectid, financialmonth);
		int count  = this.service.getCount(sql.toString());
		if(count>0){
			return ResponseResult.error("该项目在 "+ financialmonth.substring(0,7)+" 已存在记录，不能重复录入。");
		}
		return super.insert(paraMap);
	}

	/**
	  * @author: shenyouyi
	  * @date: 2020/6/16
	  * @param
	  * @description: 更新财务收入与确认
	  **/
	@Override
	@PutMapping(value = "/update")
	public ResponseResult<Object> update(@RequestBody(required = false) Map<String, Object> paraMap) {
		// 进行检验
		String id = paraMap.get("id").toString();
		Long projectid = (Long)paraMap.get("projectid");
		String financialmonth = (String)paraMap.get("financialmonth");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("projectid = {0} and financialmonth = to_date('{1}','yyyy-mm-dd hh24:mi:ss') and id != {2}", projectid, financialmonth, id);
		int count  = this.service.getCount(sql.toString());
		if(count>0){
			return ResponseResult.error("该项目在 "+ financialmonth.substring(0,7)+" 已存在记录，不能重复录入。");
		}
		return super.update(paraMap);
	}

	/**
	 * 批量确认
	 * @param paraMap
	 * @return
	 */
	@PutMapping(value = "/confirm")
	public ResponseResult<Object> confirm(@RequestBody(required = false) Map<String, Object> paraMap) {
		this.service.confirm(paraMap);
		return ResponseResult.ok("确认成功");
	}

	/**
	 * 取消确认
	 * @param paraMap
	 * @return
	 */
	@PutMapping(value = "/cancelConfirm")
	public ResponseResult<Object> cancelConfirm(@RequestBody(required = false) Map<String, Object> paraMap) {
		this.service.cancelConfirm(paraMap);
		return ResponseResult.ok("取消确认成功");
	}

	/**
	 * 自动生成
	 * @return
	 */
	@PostMapping(value = "/generate")
	public ResponseResult<Object> generate() {
		// 1.查询登录人有查看权限，当月的财政收入与确认
		Date financialmonth = getFirstDayOfMonth();
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("select p.*, pci.id as pciid ");
		sql.appendSingle("from pmproject p left join pmcostincome pci on p.id = pci.projectid and pci.financialmonth = to_date('{0}','yyyy-mm-dd') ", DateUtil.dateToString(financialmonth,"yyyy-MM-dd"));
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "PmCostIncome", this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看本人
			{
				sql.appendSingle(" and (p.projectmanagercode = '{0}' or p.areamanagercode = '{0}')", this.getUserBean().getUser().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		List<Map<String, Object>> resultList = this.service.selectExecute(sql.toString());
		resultList = resultList.stream().filter(map -> map.get("pciid") == null).collect(Collectors.toList());
		// 2.将未录入的记录，批量插入到数据库中
		List<BasicEntity> pmCostIncomeEntityList = new ArrayList<>();
		for(Map map:resultList){
			PmCostIncomeEntity costIncome = new PmCostIncomeEntity();
			Long id = Long.valueOf(map.get("id").toString());
			costIncome.setProjectid(id);
			String projectcode = (String) map.get("code");
			costIncome.setProjectcode(projectcode);
			String projectname = (String) map.get("name");
			costIncome.setProjectname(projectname);
			costIncome.setFinancialmonth(financialmonth);
			costIncome.setChecked(0);
			costIncome.setUsercode(this.getUserBean().getUser().getCode());
			costIncome.setUsername(this.getUserBean().getUser().getName());
			costIncome.setDeptcode(this.getUserBean().getDept().getCode());
			costIncome.setDeptname(this.getUserBean().getDept().getFullname());
			costIncome.setOrgcode(this.getUserBean().getOrg().getCode());
			costIncome.setOrgname(this.getUserBean().getOrg().getName());
			pmCostIncomeEntityList.add(costIncome);
		}
		if(pmCostIncomeEntityList.size()>0){
			this.service.insertBatch(pmCostIncomeEntityList);
		}
		return ResponseResult.ok("自动生成成功");
	}

	/**
	 * 得到当前日期的第一天
	 * @return
	 */
	private Date getFirstDayOfMonth() {
		LocalDate localDate = LocalDate.now();
		localDate = localDate.withDayOfMonth(1);
		ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
		return Date.from(zonedDateTime.toInstant());
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020/7/25
	 * @param: request
	 * @param: response
	 * @return void
	 * @description: 下载模板
	 * @modify:
	 */
	@PostMapping(value = "/downloadTemplate")
	public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String templatePath = "template/财务确认与收入模板.xlsx";
		String fileName = "财务确认与收入模板.xlsx";
		// 清除buffer缓存
		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
		response.setHeader("Access-Control-Expose-Headers", "FileName");
		//文件路径
		ClassPathResource cpr = new ClassPathResource(templatePath);
		BufferedInputStream inputStream = new BufferedInputStream(cpr.getInputStream());
		OutputStream out = response.getOutputStream();
		byte[] bytes = new byte[2048];
		int len;
		while((len = inputStream.read(bytes)) != -1) {
			out.write(bytes, 0, len);
		}
		inputStream.close();
		if (out != null) {
			out.flush();
		}
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-08-18
	 * @param: paraMap
	 * @param: request
	 * @param: response
	 * @return
	 * @description: 重写导出数据方法
	 * @modify:
	 */
	@Override
	@PostMapping({"/exportBigExcel"})
	public ResponseResult<Object> exportBigExcel(@RequestBody(required = false) Map<String, Object> paraMap, HttpServletRequest request, HttpServletResponse response) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
		String sord = ConvertUtil.convertToString(paraMap.get("sord"));
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(this.spellListSql(paraMap), new Object[0]);
		Map<String, String> queryMap = new HashMap();
		queryMap.put("sqlwhere", sql.toString());
		queryMap.put("sidx", sidx);
		queryMap.put("sord", sord);
		try {
			this.service.exportExcelXlsx(response, queryMap);
			return null;
		} catch (Exception var11) {
			return this.handleControllerException(var11);
		}
	}

	@Override
	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			paraMap.put("whereSql",sqlWhere);
			int totalCount = this.service.getCount(paraMap,"getPmCostIncomAndProjectCount");
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex",query.getCurrentPage());
			int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getPmCostIncomAndProject");
			} else {
				tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}
}

